package com.ctsi.security.event.organ;

import com.ctsi.commons.event.AbstractObserver;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.framework.common.startrun.ComponentFactory;
import com.ctsi.security.manager.impl.DepartAdminFetchObjIds;
import com.ctsi.security.manager.impl.DishiAdminFetchObjIds;
import com.ctsi.security.manager.impl.OrganFetchObjIds;
import com.ctsi.security.manager.impl.SecurityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@SuppressWarnings("unchecked")
public class UserJoinOrganEvent extends AbstractObserver {
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -1761441700427700350L;
	private static Logger logger = LoggerFactory.getLogger(UserJoinOrganEvent.class);
	private static OrganEventService organEventService;

	@Override
	public void onEvent(Object[] args) {
		logger.info("权限组织事件处理：组织结构用户加入组织");
		if (args.length > 1) {
			String personId = (String) args[1];
			// String personName = (String) args[2];
			String organId = (String) args[3];
			List<Map> users = (List<Map>) args[4];
			List<String> listLoginId = new ArrayList<String>();
			List<String> listLoginName = new ArrayList<String>();
			if (UtilValidate.isNotEmpty(users)) {
				for (Map user : users) {
					listLoginId.add((String) user.get("LOGINID"));
					listLoginName.add((String) user.get("FIRSTNAME") + (String) user.get("LASTNAME"));
					// 清除缓存
					OrganFetchObjIds.removeCache(user.get("LOGINID").toString());
					DishiAdminFetchObjIds.removeCache(user.get("LOGINID").toString());
					DepartAdminFetchObjIds.removeCache(user.get("LOGINID").toString());
					SecurityImpl.removeCacheUserRoles(user.get("LOGINID").toString());
				}
			}
			organEventService = this.getOrganEventService();
			organEventService.userJoinOrganEvent(organId, personId, listLoginId, listLoginName);
		}
	}

	private OrganEventService getOrganEventService() {
		if (organEventService == null) {
			organEventService = (OrganEventService) ComponentFactory.getApplicationContext().getBean("organEventService");
		}
		return organEventService;
	}

}
